package ai.tubes.iris;

import ai.tubes.iris.helper.Utilities;
import ai.tubes.iris.view.CameraPreview;
import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;

public class SolveFromCameraActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		
		mPreview 	= new CameraPreview(this);
		setContentView(mPreview);
		
		startCamera();
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			mCamera.takePicture(null, mPictureCallback, mPictureCallback);
			
			try {
				Thread.sleep(100);
			} catch (Exception e) {
				
			}
		}
		return super.onTouchEvent(event);
	}
	
	@Override
	protected void onPause() {
		stopCamera();
		super.onPause();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		startCamera();
	}
	
	private void startCamera() {
		if (mCamera == null) {
			mCamera = Camera.open();
			Camera.Parameters p = mCamera.getParameters();
            p.setPictureSize(960, 1280);
            mCamera.setParameters(p);
			mPreview.setCamera(mCamera);
			mCamera.startPreview();
		}
	}
	
	private void stopCamera() {
		if (mCamera != null) {
			mCamera.stopPreview();
			mPreview.setCamera(null);
			mCamera.release();
			mCamera = null;
		}
	}
	
	private CameraPreview mPreview;
	private Camera mCamera;
	private Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
		public void onPictureTaken(byte[] imageData, Camera c) {

			if (imageData != null) {
				Log.i("Solve Camera Act" , "Image taken size = " + imageData.length);
				mCamera.startPreview();
				
				Intent intent = new Intent();
				//intent.putExtra("image",imageData);
				Utilities.sTempImageByteArray = imageData;
				setResult(RESULT_OK, intent);
				
				finish();
			}
			Log.i("Solve Camera Act" , "Image not taken");
		}
	};
	
	public static final int REQUEST_CODE = 101;
}
